package com.apes.fico.masterdata.gl.service;

import com.apes.fico.masterdata.gl.model.*;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.fico.masterdata.gl.respository.AccountingChartDistributionCompanyRepository;
import com.apes.fico.masterdata.gl.respository.AccountingChartRepository;
import com.apes.fico.masterdata.gl.respository.AccountingOperatingChartRepository;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AccountingChartDistributionCompanyService
 * @Description TODO
 * @Author pengyb
 * @Date 2018/12/28 10:28
 * @Version 1.0
 **/
@Service("accountingChartDistributionCompanyService")
public class AccountingChartDistributionCompanyService extends DomainService {
    @Autowired
    private AccountingChartDistributionCompanyRepository accountingChartDistributionCompanyRepository;

    @Autowired
    private AccountingChartRepository accountingChartRepository;

    @Autowired
    private AccountingOperatingChartRepository accountingOperatingChartRepository;

    /**
     * 保存
     *
     * @param request
     * @return
     */
    public AccountingChartDistributionCompany save(SimpleRequest request) {
        checkSave(request);
        AccountingChartDistributionCompany accountingChartDistributionCompany = request.getO(AccountingChartDistributionCompany.class);
        accountingChartDistributionCompany.setCreateDate(new Date());
        List<AccountingChart> accountingCharts = accountingChartRepository.findAllByAccSystem_Id(accountingChartDistributionCompany.getAccSystem().getId());//查出集团科目表信息
        List<AccountingOperatingChart> accountingOperatingCharts = new ArrayList<>();
        accountingCharts.stream().forEach(accChart -> {  // 遍历转化集团表数据为运营表数据；先使父级科目与辅助核算项为空
            AccountingOperatingChart accOperChart = new AccountingOperatingChart();
            accOperChart.setCode(accChart.getCode());
            accOperChart.setAccSystem(accChart.getAccSystem());
            accOperChart.setCompany(accountingChartDistributionCompany.getCompany());
            accOperChart.setName(accChart.getName());
            accOperChart.setDisplayName(accChart.getDisplayName());
            accOperChart.setBalanorient(accChart.getBalanorient());
            accOperChart.setValid(true);
            accOperChart.setInheritFlag(false);
            accOperChart.setClasses(accChart.getClasses());
            accOperChart.setAccGroup(accChart.getAccGroup());
            accOperChart.setFinalFlag(accChart.isFinalFlag());
            accOperChart.setId(accOperChart.getCompany().getId() + "." + accOperChart.getCode());
            if (accChart.getParent() != null) {
                AccountingOperatingChart parent = new AccountingOperatingChart();
                parent.setId(accOperChart.getCompany().getId() + "." + accChart.getParent().getCode());
                accOperChart.setParent(parent);
            }
            if (accChart.getAccChartAuxiliaries() != null) {
                List<AccountingOperatingChartAuxiliary> accAux = new ArrayList<>();
                accChart.getAccChartAuxiliaries().stream().forEach(accAuxs -> {
                    AccountingOperatingChartAuxiliary accOpChartAuxiliary = new AccountingOperatingChartAuxiliary();
                    AccountingOperatingChart accountingOperatingChart = new AccountingOperatingChart();
                    accountingOperatingChart.setId(accOperChart.getCompany().getId() + "." + accAuxs.getAccChart().getCode());
                    accOpChartAuxiliary.setSequence(accAuxs.getSequence());
                    accOpChartAuxiliary.setAccAuxiliaryProject(accAuxs.getAccAuxiliaryProject());
                    accOpChartAuxiliary.setAccOperatingChart(accountingOperatingChart);
                    accAux.add(accOpChartAuxiliary);
                });
                accOperChart.setAuxFlag(true);
                accOperChart.setAccOperatingChartAuxiliaryList(accAux);
            }
            accountingOperatingCharts.add(accOperChart);

        });
        accountingOperatingChartRepository.save(accountingOperatingCharts);//保存转化后的运营科目表,此时运营科目表已有数据

        return accountingChartDistributionCompanyRepository.saveAndFlush(accountingChartDistributionCompany);
    }

    /**
     * 修改
     *
     * @param request
     * @return
     */
    public AccountingChartDistributionCompany update(SimpleRequest request) {
        checkData(request);
        AccountingChartDistributionCompany accountingChartDistributionCompany = request.getO(AccountingChartDistributionCompany.class);
        accountingChartDistributionCompany.setUpdateDate(new Date());
        return accountingChartDistributionCompanyRepository.saveAndFlush(accountingChartDistributionCompany);
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        checkData(request);
        AccountingChartDistributionCompany accountingChartDistributionCompany = request.getO(AccountingChartDistributionCompany.class);
        accountingChartDistributionCompanyRepository.delete(accountingChartDistributionCompany.getId());
        return "删除成功";
    }

    /**
     * 检查
     *
     * @param request
     */
    public void checkData(SimpleRequest request) {
        AccountingChartDistributionCompany accountingChartDistributionCompany = accountingChartDistributionCompanyRepository.findOne((String) request.get("id"));
        if (accountingChartDistributionCompany == null)
            throw new RuntimeException(accountingChartDistributionCompany.getId() + "不存在");
        if (accountingChartDistributionCompany.getVersion() != (int) request.get("version"))
            throw new RuntimeException(accountingChartDistributionCompany.getId() + "已更新或已删除");
    }

    /**
     * 检查save
     *
     * @param request
     */
    public void checkSave(SimpleRequest request) {
        AccountingChartDistributionCompany company = request.getO(AccountingChartDistributionCompany.class);
        List<AccountingChartDistributionCompany> accountingChartDistributionCompanies = accountingChartDistributionCompanyRepository.findAllByAccSystem_IdAndCompany_Id(company.getAccSystem().getId(), company.getCompany().getId());
        if (!accountingChartDistributionCompanies.isEmpty()) throw new RuntimeException("不可在同一公司同一个科目表下生成多个运营科目表！");
    }

    public AccountingSystem getAccountingSystem(PartyRole company) {
        Map filters = MapUtil.mapper("company", company);
        AccountingChartDistributionCompany acdc = accountingChartDistributionCompanyRepository.findOne(JpaDsl.toCriteria(filters)).orElse(null);
        if (acdc == null) return null;
        return acdc.getAccSystem();
    }


    public Page<Map<String, Object>> findAllParty(SimpleRequest request) {
        return accountingChartDistributionCompanyRepository.findAllParty(PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 根据公司查询
     *
     * @param request
     * @return
     */
    public Map<String, Object> findByCompany(SimpleRequest request) {

        Map<String, Object> map = accountingChartDistributionCompanyRepository.findByCompany(request.get("company"));
        if (map != null && map.size() != 0 && !map.isEmpty()) {
            String[] accIdRuleArr = map.get("accIdRule").toString().split("/");
            for (int i = 0; i < accIdRuleArr.length; i++) {
                accIdRuleArr[i] = (i + 1) + "";
            }
            map.put("accIdRuleArr",accIdRuleArr);
            return map;
        }
        return null;
    }
}
